package com.sziit.se.highconcurrency.user.application.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.sziit.se.highconcurrency.common.entity.LoginRsp;
import com.sziit.se.highconcurrency.common.entity.User;
import com.sziit.se.highconcurrency.common.entity.UserInfoVo;
import com.sziit.se.highconcurrency.common.exception.CustomException;
import com.sziit.se.highconcurrency.common.tool.JwtUtils;
import com.sziit.se.highconcurrency.common.tool.LocalUser;
import com.sziit.se.highconcurrency.common.tool.PasswordUtils;
import com.sziit.se.highconcurrency.user.application.mapper.UserMapper;
import com.sziit.se.highconcurrency.common.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

import static cn.hutool.core.lang.Validator.isMobile;
import static com.sziit.se.highconcurrency.common.constant.SystemConstants.SALT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongchunkeng
 * @since 2022-09-21
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final UserMapper userMapper;

    @Override
    public List<User> getAllData() {
        return userMapper.getAllData();
    }

    @Override
    public Boolean insertUser(String userName, String password, String phone) {
        String userId = UUID.randomUUID().toString();
        String salt = SALT;
        //生成密码
        String passwordMd5 = PasswordUtils.generate(password, salt);
        return userMapper.insertUser(userId, userName, passwordMd5,phone);
    }

    @Override
    public User getOneData(String userName) {
        return userMapper.getOneData(userName);
    }

    @Override
    public User getById(String userId) {
        return userMapper.getById(userId);
    }

    @Override
    public Boolean register(String userName, String password, String phone) {
        if (checkPhone(phone)) {
            //生成密码盐
//            String salt = RandomUtil.randomString(6);
            String salt = SALT;
            //生成密码
            String passwordMd5 = PasswordUtils.generate(password, salt);
            //保存用户信息
            User user = User.builder()
                    .userId(UUID.randomUUID().toString())
                    .userName(userName)
                    .phone("手机号码" + phone)
                    .password(passwordMd5)
                    .build();
            this.save(user);
            //返回用户信息
            return true;
        } else {
            throw new CustomException("手机号码校验失败");
        }
    }

    @Override
    public LoginRsp login(String userName, String password) {
        //根据手机号查询用户信息
        User user = this.lambdaQuery().eq(User::getUserName, userName).one();
        //判断用户信息是否为空
        if (user != null) {
            //判断密码是否正确
            if (PasswordUtils.matches(password, SALT, user.getPassword())) {
                //返回用户信息
                return LoginRsp.builder()
                        //生成token
                        .token(JwtUtils.sign(user.getUserId().toString(), user.getPassword()))
                        .build();
            } else {
                throw new CustomException("密码错误");
            }
        } else {
            throw new CustomException("该用户未注册");
        }
    }

    @Override
    public UserInfoVo updateUser(String userName, String password, String phone) {
        User user = LocalUser.getUserNotNull();

        if (userName != null) {
            user.setUserName(userName);
        }

        if (phone != null) {
            user.setPhone(phone);
        }

        if (password != null) {
            String salt = SALT;
            //生成密码
            String passwordMd5 = PasswordUtils.generate(password, salt);
            user.setPassword(passwordMd5);
        }

        if (updateById(user)) {
            // 返回用户信息
            return user.toVo();
        } else {
            throw new CustomException("修改用户信息失败");
        }
    }

    @Override
    public UserInfoVo userInfo() {
        User user = LocalUser.getUserNotNull();
        if (user != null) {
            return user.toVo();
        } else {
            throw new CustomException("获取登录用户信息失败");
        }
    }


    /**
     * 判断手机号是否被注册
     *
     * @param phone 手机号
     * @return boolean
     */
    private boolean checkPhone(String phone) {
        //判断手机号是否合法
        if (isMobile(phone)) {
            //根据手机号查询用户信息
            User user = this.lambdaQuery().eq(User::getPhone, phone).one();
            //判断用户信息是否为空
            //手机号可以注册
            if (user == null) {
                return true;
            } else {
                throw new CustomException("该手机号已被注册");
            }
        }
        return false;
    }
}
